package cn.stylefeng.guns.modular.business.frequency.cmcompany.controller;

import cn.stylefeng.guns.core.enums.ReturnCode;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.AndaPageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.entity.CmCompany;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.model.param.CompanyDTO;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.model.param.CompanyOrderDTO;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.model.param.OrderLinkmanVO;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.model.param.UnCheckCompanyVO;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.model.result.CompanyVO;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.model.result.LinkmanCheckVO;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.model.result.PkgCompanyOrder;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.service.CmCompanyService;
import cn.stylefeng.guns.modular.business.frequency.cmcompanyline.entity.CmCompanyLine;
import cn.stylefeng.guns.modular.business.frequency.cmdriver.entity.CmDriver;
import cn.stylefeng.guns.modular.business.frequency.cmdriver.service.CmDriverService;
import cn.stylefeng.guns.modular.business.frequency.cmlinkman.entity.CmLinkman;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author jzy
 * @Date 2021/7/7 0007
 **/
@Api(tags = "企业通讯录")
@RestController
@RequestMapping("/api/company")
public class CompanyController {

    @Resource
    private CmCompanyService companyService;
    @Autowired
    private BusinessUtil businessUtil;
    @Autowired
    private CmDriverService driverService;


    @ApiOperation(value = "企业通讯录分页列表")
    @GetMapping
    public ResponseData getCompanyListPage(CompanyDTO companyDTO) {

        if (StringUtils.isBlank(companyDTO.getColumn()) ) {
            // 默认排序
            companyDTO.setColumn("c.create_time");
        }
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        return companyService.getCompanyListPage(companyDTO,empByOrgList);
    }

    @ApiOperation(value = "联系人分页列表")
    @GetMapping("{companyId}/linkman")
    public ResponseData getLinkmanListPage( @PathVariable String companyId, CompanyDTO companyDTO) {
        if (StringUtils.isBlank(companyDTO.getColumn())) {
            companyDTO.setColumn("l.id");
            companyDTO.setAsc(false);
        }
        return companyService.getLinkmanListPage(companyId, companyDTO);
    }
    @ApiOperation(value = "企业通讯录新增")
    @PostMapping
    public ResponseData companyAdd(@RequestBody @Validated CompanyVO companyVO) {
        StringBuilder errorMsg = new StringBuilder();
        if (!companyService.checkCompanyAdd(companyVO, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        companyService.addCompany(companyVO);
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "企业通讯录编辑")
    @PutMapping
    public ResponseData companyUpdate(@RequestBody @Validated CompanyVO companyVO) {
        StringBuilder errorMsg = new StringBuilder();
        if (!companyService.checkCompanyUpdate(companyVO, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        companyService.updateCompany(companyVO);
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "设置为内置公司")
    @PostMapping("/hasSelf")
    public ResponseData setHasSelf(@RequestBody  CompanyVO companyVO) {
        companyService.setHasSelf(companyVO.getId());
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "企业通讯录编辑详情")
    @GetMapping("/single/{id}")
    public ResponseData getCompanyDetail(@PathVariable String id) {
        CompanyVO companyVO = companyService.getCompanySingleDetail(id);
        return ResponseData.andaSuccess(companyVO);
    }

    @ApiOperation(value = "通讯录删除")
    @DeleteMapping("/{id}")
    public ResponseData deleteCompany(@PathVariable String id) {
        CmCompany company = companyService.getCompanyById(id);
        if (company.getHasSelf() == 1) {
            return ResponseData.andaError("内置公司不可删除");
        }
        companyService.deleteCompany(id);
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "联系人新增")
    @PostMapping("/linkman")
    public ResponseData linkmanAdd(@RequestBody CompanyVO companyVO) {
        StringBuilder errorMsg = new StringBuilder();
        if (!companyService.checkLinkmanAdd(companyVO, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        companyService.addLinkman(companyVO);
        return ResponseData.andaSuccess();
}

    @ApiOperation(value = "联系人编辑详情")
    @GetMapping("/linkman/single/{id}")
    public ResponseData getLinkmanSingleDetail(@PathVariable String id) {
        CmLinkman linkman = companyService.getLinkmanSingleDetail(id);
        return ResponseData.andaSuccess(linkman);
    }

    @ApiOperation(value = "联系人删除")
    @DeleteMapping("/linkman/{id}")
    public ResponseData linkmanDelete(@PathVariable String id) {
        CmLinkman linkman = companyService.getLinkmanSingleDetail(id);
        companyService.deleteLinkman(id);
        //清除用户缓存 todo
        //userService.delCaches(linkman.getId(), linkman.getPhone());
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "联系人编辑")
    @PutMapping("/linkman")
    public ResponseData linkmanUpdate(@RequestBody @Validated CmLinkman linkman) {
        StringBuilder errorMsg = new StringBuilder();
        if (!companyService.checkLinkmanUpdate(linkman, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        companyService.updateLinkman(linkman);
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "司机列表")
    @GetMapping("{companyId}/driver")
    public ResponseData getDriverListPage(@PathVariable String companyId, CompanyDTO companyDTO) {
        List<CmDriver> list = companyService.getDriverListPage(companyId, companyDTO);
        return ResponseData.andaSuccess(list);
    }

    @ApiOperation(value = "司机新增")
    @PostMapping("/driver")
    public ResponseData driverAdd(@RequestBody @Validated CmDriver driver) {
        StringBuilder errorMsg =new StringBuilder();
        if (!companyService.checkDriverAdd(driver, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        companyService.addDriver(driver);
        return ResponseData.andaSuccess(driver);
    }


    @ApiOperation(value = "司机批量新增")
    @PostMapping("/driverList2")
    public ResponseData driverListAdd(@RequestBody  CmDriver driver) {
        List<CmDriver> driverList = driver.getDriverList();
        List<CmDriver> cmDriverList = driverList.stream()
                .collect(Collectors.toMap(CmDriver::getPhone, p -> p, (p1, p2) -> p1))
                .values()
                .stream()
                .collect(Collectors.toList());
        for(CmDriver cmDriver : cmDriverList){
            StringBuilder errorMsg =new StringBuilder();
            if (!companyService.checkDriverAdd(cmDriver, errorMsg)) {
                return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
            }
        }
        driverService.saveBatch(cmDriverList);
        return ResponseData.andaSuccess();
    }








    @ApiOperation(value = "司机信息编辑")
    @PutMapping("/driver")
    public ResponseData driverUpdate(@RequestBody @Validated CmDriver driver) {
        StringBuilder errorMsg = new StringBuilder();
        if (!companyService.checkDriverUpdate(driver, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        companyService.updateDriver(driver);
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "司机删除")
    @DeleteMapping("/driver/{id}")
    public ResponseData driverDelete(@PathVariable String id) {
        CmDriver driver = companyService.getDriverDetail(id);
        companyService.deleteDriver(id);
        //清除用户缓存 TODO
        //userService.delCaches(driver.getId(), driver.getPhone());
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "企业订单分页列表")
    @GetMapping("/{companyId}/order")
    public ResponseData getCompanyOrderListPage(@PathVariable String companyId, CompanyOrderDTO companyOrderDTO) {
        if (StringUtils.isBlank(companyOrderDTO.getColumn()) ) {
            companyOrderDTO.setColumn("id");
            companyOrderDTO.setAsc(false);
        }
        Page<PkgCompanyOrder> list = companyService.getCompanyOrderListPage(companyId, PageFactory.defaultPage(), companyOrderDTO);
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(list,companyOrderDTO));
    }

    @ApiOperation(value = "添加待审核通讯录")
    @PostMapping("/un-check")
    public ResponseData AddUnCheckLinkman(@RequestBody @Validated UnCheckCompanyVO companyVO) {
        StringBuilder errorMsg = new StringBuilder();
        if (!companyService.checkUnCheckLinkmanAdd(companyVO, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        UnCheckCompanyVO result = companyService.addUnCheckLinkman(companyVO);
        return ResponseData.andaSuccess(result);
    }

    @ApiOperation(value = "联系人审核详情")
    @GetMapping("/linkman/check/{id}")
    public ResponseData linkmanCheckDetail(@PathVariable String id) {
        LinkmanCheckVO linkmanCheckVO = companyService.getLinkmanCheckDetail(id);
        return ResponseData.andaSuccess(linkmanCheckVO);
    }

    @ApiOperation(value = "联系人审核")
    @PutMapping("linkman/check")
    public ResponseData linkmanCheck(@RequestBody @Validated LinkmanCheckVO linkmanCheckVO) {
        StringBuilder errorMsg = new StringBuilder();
        if (!companyService.checkLinkmanCheck(linkmanCheckVO, errorMsg)) {
            return ResponseData.andaError(ReturnCode.RETURN_PARAM_ERROR.code,errorMsg.toString());
        }
        companyService.checkLinkman(linkmanCheckVO);
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "已审核公司列表")
    @GetMapping("/has-check")
    public ResponseData hasCheckedCompanyList() {
        List<UnCheckCompanyVO> list = companyService.getHasCheckCompanyList();
        return ResponseData.andaSuccess(list);
    }

    @ApiOperation(value = "公司名称、联系人、电话模糊搜索查询")
    @GetMapping("/order/suggest")
    public ResponseData getOrderLinkmanSuggest(OrderLinkmanVO orderLinkmanVO) {
        List<OrderLinkmanVO> list = companyService.getOrderLinkmanSuggest(orderLinkmanVO);
        return ResponseData.andaSuccess(list);
    }

    @ApiOperation(value = "公司名称、联系人、电话模糊搜索查询/网点搜索/运单号搜索")
    @GetMapping("/order/suggestAll")
    public ResponseData getOrderLinkmanSuggestAll(OrderLinkmanVO orderLinkmanVO) {
        List<OrderLinkmanVO> list = companyService.getOrderLinkmanSuggestAll(orderLinkmanVO);
        return ResponseData.andaSuccess(list);
    }

    @ApiOperation(value = "根据联系人ID数组查询")
    @GetMapping("/multi-linkman")
    public ResponseData getLinkmanListByIds(@RequestParam("linkmanIds") List<String> linkmanIds) {
        List<OrderLinkmanVO> list = companyService.getLinkmanListByIds(linkmanIds);
        return ResponseData.andaSuccess(list);
    }

    @ApiOperation(value = "获取公司线路信息")
    @GetMapping("/{companyId}/line")
    public ResponseData getCompanyLineList(@PathVariable String companyId) {
        List<CmCompanyLine> list = companyService.getCompanyLineListById(companyId);
        return ResponseData.andaSuccess(list);
    }

    @ApiOperation(value = "通讯录导入")
    @PostMapping("/import-excel")
    public ResponseData importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        companyService.importExcel(file);
        return ResponseData.andaSuccess( "导入成功");
    }

    @ApiOperation(value = "修改联系人所属用户")
    @PutMapping("/linkman/owner-user")
    public ResponseData changeCreateUser(@RequestBody CmLinkman linkman) {
        if (linkman == null || linkman.getId()==null || linkman.getCreateUser()==null) {
            return ResponseData.andaSuccess("参数错误");
        }
        companyService.changeLinkmanOwnerUser(linkman);
        return ResponseData.andaSuccess();
    }
}
